package com.ksc.storekeeper.client.view.components;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasCaption;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.ksc.storekeeper.client.view.validation.ValidatingTextArea;
import com.ksc.storekeeper.client.view.validation.Validation;

public class FormItemTextArea extends Composite implements HasCaption {

	private static FormItemTextAreaUiBinder uiBinder = GWT.create(FormItemTextAreaUiBinder.class);

	interface FormItemTextAreaUiBinder extends UiBinder<Widget, FormItemTextArea> {
	}

	@UiField
	FlowPanel panel;
	@UiField
	Label label;
	@UiField
	ValidatingTextArea input;
	@UiField
	HTML error;

	private boolean validation = false;
	private boolean required = false;

	public FormItemTextArea() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	public boolean validate() {
		boolean valid = true;
		if (validation) {
			input.setRequired(required);
			valid = input.validate().equals(Validation.VALID) && valid;
			error.setText(input.getErrorMessage());
		}
		return valid;
	}

	public String getText() {
		return input.getText().trim();
	}

	public void setText(String text) {
		input.setText(text.trim());
	}

	@Override
	public String getCaption() {
		return label.getText();
	}

	@Override
	public void setCaption(String caption) {
		label.setText(caption.trim());
	}

	public FlowPanel getPanel() {
		return panel;
	}

	public void setPanel(FlowPanel panel) {
		this.panel = panel;
	}

	public Label getLabel() {
		return label;
	}

	public void setLabel(Label label) {
		this.label = label;
	}

	public ValidatingTextArea getInput() {
		return input;
	}

	public void setInput(ValidatingTextArea input) {
		this.input = input;
	}

	public HTML getError() {
		return error;
	}

	public void setError(HTML error) {
		this.error = error;
	}

	public void setMinLength(int minLength) {
		input.setMinLength(minLength);
	}

	public void setMaxLength(int maxLength) {
		input.setMaxLength(maxLength);
	}

	public boolean isValidation() {
		return validation;
	}

	public boolean isRequired() {
		return required;
	}

	public void setValidation(boolean validation) {
		this.validation = validation;
	}

	public void setRequired(boolean required) {
		this.required = required;
	}

	public void removeInvalid() {
		error.setText("");
		input.removeInvalid();
	}

	public void clear() {
		error.setText("");
		setText("");
		input.removeInvalid();
	}

}
